<template>
  <div class="sensitive-result-detail">
    <el-container>
      <el-aside width="400px" class="mb-0 border-1px border-#ebebeb border-solid bg-#fff p-0">
        <div
          class="border-b-1px border-b-#ebebeb border-b-solid bg-#F9FAFC px-20px text-14px"
          style="line-height: 41px"
        >
          资产名称
        </div>
        <div class="h-32px p-5px">
          <ns-input v-model="keyword" clearable placeholder="请输入名称" class="input-with-select">
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </ns-input>
        </div>
        <div class="bg-color h-540px flex pl10px" style="overflow-y: scroll">
          <el-tree
            style="flex: 1"
            v-if="showTree && JSON.stringify(info) !== '{}'"
            ref="assetTree"
            class="max-w-full"
            @node-click="getInfo"
            highlight-current
            :data="treeData"
            :props="prop"
            v-loading="isLoading"
          />
          <el-icon v-if="showTreeIp" style="height: 36px; width: 36px">
            <Hide @click="showTreeIp = !showTreeIp" />
          </el-icon>
          <el-icon v-else style="height: 36px; width: 36px">
            <View @click="showTreeIp = !showTreeIp" />
          </el-icon>
        </div>
      </el-aside>
      <el-main>
        <el-card
          style="min-height: 190px"
          :body-style="{ padding: '15px 20px 20px 20px !important' }"
        >
          <template #header>
            <div class="card-header text-14px">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  width: 20%;
                "
              >
                <span v-if="showTitleIp">{{
                  `${info.ip}:${info.port}-${info.assetTypeName}`
                }}</span>
                <span v-else style="font-weight: bolder">***********</span>
                <el-icon v-if="showTitleIp">
                  <Hide @click="showTitleIp = !showTitleIp" />
                </el-icon>
                <el-icon v-else>
                  <View @click="showTitleIp = !showTitleIp" />
                </el-icon>
              </div>
            </div>
          </template>
          <div>
            <div class="pb-5px pt-10px text-14px">
              <template v-if="nodeType === 'table'">
                <div class="leh-32">
                  <label class="color-info">表名：</label>
                  <span>{{ currentInfo.table || '--' }}</span>
                </div>
                <div class="leh-32">
                  <label class="color-info">表描述：</label>
                  <span>{{ currentInfo.remark || '--' }}</span>
                </div>
              </template>
              <div v-if="nodeType === 'table' || nodeType === 'schema'" class="leh-32">
                <label class="color-info">schema：</label>
                <span>{{ currentInfo.schema || '--' }}</span>
              </div>
              <div v-if="nodeType !== 'asset' && nodeType !== 'db'" class="leh-32">
                <label class="color-info">数据库名：</label>
                <span>{{ currentInfo.db || '--' }}</span>
              </div>
              <div v-else-if="nodeType == 'db'" class="leh-32">
                <label class="color-info">数据库名：</label>
                <span>{{ currentInfo.name || '---' }}</span>
              </div>
              <div class="leh-32">
                <label class="color-info">资产地址：</label>
                <div style="display: flex; align-items: center">
                  <div style="display: inline; width: 150px" v-if="showDetailIp"
                    >{{ info.ip }}:{{ info.port }}</div
                  >
                  <div v-else style="font-weight: bolder; display: inline; width: 150px"
                    >***********</div
                  >
                  <el-icon v-if="showDetailIp">
                    <Hide @click="showDetailIp = !showDetailIp" />
                  </el-icon>
                  <el-icon v-else>
                    <View @click="showDetailIp = !showDetailIp" />
                  </el-icon>
                </div>
              </div>
              <div class="leh-32">
                <label class="color-info">资产类型：</label>
                <span>{{ info.assetTypeName }}</span>
              </div>
              <div class="leh-32">
                <label class="color-info">数据源来源：</label>
                <span>{{ info.sourceName }}</span>
              </div>
              <div class="leh-32">
                <label class="color-info">归属机构：</label>
                <span>{{ info.department }}</span>
              </div>
              <div class="leh-32">
                <label class="color-info">归属系统：</label>
                <span>{{ info.system }}</span>
              </div>
            </div>
          </div>
        </el-card>
        <el-card v-show="['db', 'schema'].includes(nodeType) && showTable" class="mt-10px">
          <AsyncTable
            ref="tableRef"
            v-bind="tableOption"
            :auto-request="false"
            :fetchData="fetchData"
          />
        </el-card>
        <el-card v-if="nodeType === 'table'" class="risk-card box-card mt-10px">
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane name="table-field" label="字段列表">
              <AsyncTable v-bind="fieldTable" v-if="activeTab == 'table-field'" />
            </el-tab-pane>
            <el-tab-pane name="table-eg" label="抽样数据">
              <el-auto-resizer>
                <template #default="{ width }">
                  <el-table-v2
                    :columns="exampleTable.columns"
                    :data="exampleTable.data"
                    :width="width"
                    :height="280"
                    fixed
                  />
                </template>
              </el-auto-resizer>
              <!-- <AsyncTable v-bind="exampleTable" v-if="activeTab == 'table-eg'" /> -->
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="jsx" setup>
import { useRoute } from 'vue-router'
import { ref } from 'vue'
import { Search, Hide, View } from '@element-plus/icons-vue'
import { getMeta, getMetaChild, getTablePage } from '@/api/asset/taskManage/dataCollect'
import { renderFinger, renderLevel } from '@/utils/commonRender'
const route = useRoute()
const showTreeIp = ref(false)
const showTitleIp = ref(false)
const showDetailIp = ref(false)
const props = defineProps({
  historyId: {
    type: String,
    default: ''
  },
  info: {
    type: Object,
    default: () => {}
  },
  showDetail: {
    type: Boolean,
    default: false
  },
  detailInfo: {
    type: Object,
    default: () => {}
  },
  levelList: {
    type: Array,
    default: () => []
  },
  collectionAssetId: {
    type: String,
    default: ''
  }
})
const tableInfo = ref({})
const tableOption = reactive({
  columns: [
    {
      prop: 'table',
      label: '表名称'
    },
    {
      prop: 'remark',
      label: '表描述'
    },
    {
      label: '分类',
      prop: 'classification'
    },
    {
      label: '分级',
      render: renderLevel
    },
    { label: '', width: '60px' }
  ],
  border: true,
  isPage: true,
  'max-height': '280px',
  data: []
})
const fieldTable = reactive({
  columns: [
    {
      prop: 'column',
      label: '字段名称'
    },
    {
      prop: 'comment',
      label: '字段描述'
    },
    {
      label: '分类',
      prop: 'classification'
    },
    {
      label: '分级',
      render: renderLevel
    },
    { label: '', width: '60px' }
  ],
  border: true,
  isPage: false,
  'max-height': '280px',
  data: []
})
const exampleTable = reactive({
  columns: [
    {
      key: `column`,
      title: '列名称',
      width: 130
    },
    {
      key: `comment`,
      title: '备注',
      width: 130
    },
    {
      label: '分类',
      prop: 'classification'
    },
    {
      label: '分级',
      render: renderLevel
    },
    { label: '', width: '60px' }
  ],
  border: true,
  isPage: false,
  'max-height': '280px',
  data: []
})
const treeData = ref([])
const tableRef = ref()
const parentId = ref()
const showTable = ref(true)
const showTree = ref(true)
const keyword = ref('')
const isLoading = ref(false)
const prop = {
  label: 'name',
  children: 'child',
  isLeaf: function (data, node) {
    return !data.hasChild
  }
}
const activeTab = ref('table-field')
const nodeType = ref('asset')

const handleSearch = async () => {
  const data = await getMeta({
    parentId: route.query.collectionAssetId || props.collectionAssetId,
    historyId: props.historyId,
    datasourceId: route.query.datasourceId,
    collectionAssetId: route.query.collectionAssetId || props.collectionAssetId,
    keyword: keyword.value
  })
  if (keyword.value === '' || keyword.value === null) {
    treeData.value = [
      {
        name: `${props.info.ip}:${props.info.port}-${props.info.assetTypeName}`,
        hasChild: true,
        id: route.query.collectionAssetId || props.collectionAssetId,
        child: data
      }
    ]
  } else {
    treeData.value = data
  }
}

const fetchData = async ({ page, pageSize }) => {
  const { data, count } = await getTablePage({
    page: page,
    pageSize,
    parentId: parentId.value,
    historyId: props.historyId,
    datasourceId: route.query.datasourceId,
    collectionAssetId: route.query.collectionAssetId || props.collectionAssetId,
    keyword: keyword.value
  })
  showTable.value = data?.length > 0 ? true : false
  return { data, count }
}
const currentInfo = ref()
const getInfo = async (node) => {
  showDetailIp.value = false
  nodeType.value = node.dataType || 'asset'
  currentInfo.value = node
  if (node.dataType) {
    if (['db', 'schema'].includes(node.dataType)) {
      parentId.value = node.id
      tableRef.value.resetPage()
      tableRef.value.fetchData()
    } else if (node.dataType === 'table') {
      tableInfo.value = node
      const data = await getMetaChild({
        parentId: node.id,
        historyId: props.historyId,
        datasourceId: route.query.datasourceId,
        collectionAssetId: route.query.collectionAssetId || props.collectionAssetId,
        keyword: keyword.value
      })
      fieldTable.data = data
      initExampleTable(data)
    }
  }
}

function initExampleTable(data) {
  const arr = []
  const samples = data[0].samples
  const allKey = data.map((item) => item.column)
  const allData = data.map((item) => {
    return item.samples
  })
  for (const i in samples) {
    const row = {}
    for (const j in allKey) {
      row[allKey[j]] = allData[j][i]
    }
    arr.push(row)
  }
  exampleTable.columns = data.map((item) => {
    return {
      key: item.column,
      dataKey: item.column,
      title: item.column,
      width: 150
    }
  })
  exampleTable.data = arr
}
watch(
  props,
  async (newVal) => {
    isLoading.value = true
    keyword.value = ''
    showTreeIp.value = false
    const data = await getMeta({
      parentId: route.query.collectionAssetId || props.collectionAssetId,
      historyId: props.historyId,
      datasourceId: route.query.datasourceId,
      collectionAssetId: route.query.collectionAssetId || props.collectionAssetId,
      keyword: keyword.value
    })
    console.log(props.info.ip, props.info.port, props.info.assetTypeName)
    treeData.value = [
      {
        name: `${showTreeIp.value ? props.info.ip + ':' + props.info.port : '***********'}-${props.info.assetTypeName}`,
        hasChild: true,
        id: route.query.collectionAssetId || props.collectionAssetId,
        child: data
      }
    ]
    console.log(1)
    isLoading.value = false
  },
  { immediate: true }
)
watch(showTreeIp, (newVal) => {
  treeData.value[0].name = `${showTreeIp.value ? props.info.ip + ':' + props.info.port : '***********'}-${props.info.assetTypeName}`
})
</script>
<style lang="scss">
.sensitive-result-detail {
  .leh-32 {
    width: 100%;
    height: 32px;
    line-height: 24px;
    margin-bottom: 10px;
    label {
      display: block;
      width: 150px;
      float: left;
    }
    span {
      float: left;
      display: block;
      text-wrap: wrap;
      width: calc(100% - 150px);
      overflow-wrap: break-word;
    }
  }
  .el-card__header {
    background: #f9fafc;
  }
  .el-card .el-card__body {
    padding: 10px !important;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  a,
  a:focus,
  a:hover {
    color: #409eff;
  }
  .el-tree-node__content {
    height: 36px;
    min-width: max-content;
  }
  .flow-tree > .el-tree-node > .el-tree-node__children {
    overflow: visible !important;
  }
  .text-point::before {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    vertical-align: middle;
    background: #0f72e6;
    border-radius: 100%;
    margin-right: 5px;
  }
  .el-main {
    padding: 0px !important;
    padding-left: 10px !important;
  }
  label.color-info {
    width: 90px;
    text-align: right;
    display: inline-block;
  }
  .el-card.risk-card {
    .el-card__body {
      padding: 0 !important;
    }
    .el-tabs--border-card {
      border: none;
    }
  }
  .json-data-tab .el-tabs__nav {
    float: right;
  }
}
</style>
